﻿Imports Lourdes.BackEnd.BC
Imports Lourdes.BackEnd.Modelo
Imports Lourdes.BackEnd.View
Imports Infragistics.Win.UltraWinGrid

Public Class frmProductosBuscar
  'Public Event ProductoSeleccionado(ByVal pProducto As vProducto)
  Public Event RecargarGrillaProductos(ByVal pProductos As vLstProductos)
  Private _ListPrecioId As Integer
  Private _ProductosEnFactura As vLstProductos
  Private ProductoSel As vProducto = Nothing
  Private AgregarAFactura As Boolean = False
  Private _ModoEdicion As Boolean = False
  Public Property ListaPrecioId() As Integer
    Get
      Return _ListPrecioId
    End Get
    Set(ByVal value As Integer)
      _ListPrecioId = value
    End Set
  End Property

  Public Sub GetProductoByFilters(ByVal pListPreciosId As Integer, ByVal pMercNum As String, ByVal pMercDesc As String, pProductosGridFactura As vLstProductos, _
                                  Optional pParent As Form = Nothing, Optional pModoEdicion As Boolean = False)
    Try
      LimpiarControles()
      _ProductosEnFactura = pProductosGridFactura
      _ModoEdicion = pModoEdicion
      btnProductoAlterntivo.Enabled = False
      txtCodigo.Text = pMercNum
      txtDescripcion.Text = pMercDesc
      'txtCodigo.Focus()
      CargarGrid()

      If pParent IsNot Nothing Then
        ShowDialog(pParent)
      Else
        ShowDialog()
      End If

    Catch ex As Exception
      Utils.ManejoErrores(ex)
    End Try
  End Sub

  Public Sub CargarGrid()
    Dim bcMerc As BC_Mercaderia
    Dim lstvProd As List(Of vProducto)
    Try
      bcMerc = New BC_Mercaderia
      If txtCodigo.Text.Trim <> "" OrElse txtDescripcion.Text <> "" Then
        lstvProd = bcMerc.GetMercViewByFilters(_ListPrecioId, txtDescripcion.Text, txtCodigo.Text)
        CargarGrid(lstvProd)

        If grdDatos.Rows.Count > 0 Then
          grdDatos.Focus()
          grdDatos.Rows.FirstOrDefault.Selected = True
        Else
          txtCodigo.Focus()
        End If

        grdDatos_AfterSelectChange(grdDatos, Nothing)
        'txtCodigo.Focus()
      End If
    Catch ex As Exception
      Utils.ManejoErrores(ex)
    End Try
  End Sub

  Private Sub CargarGrid(ByVal pLstvProducto As List(Of vProducto))
    Try
      With grdDatos
        .DataSource = pLstvProducto
        .DataBind()
        .Focus()
        If pLstvProducto.Count > 0 Then
          .Rows.FirstOrDefault.Selected = True
        End If
      End With
    Catch ex As Exception
      Utils.ManejoErrores(ex)
    End Try
  End Sub

  Private Sub btnAceptar_Click(sender As System.Object, e As System.EventArgs) Handles btnAceptar.Click
    If grdDatos.Rows.Count > 0 Then
      CargarDatosDesdeControles()

      If AgregarAFactura Then
        _ProductosEnFactura.Add(ProductoSel)
        ProductoSel = Nothing
      End If
      AgregarAFactura = False
      LimpiarControles()
      RaiseEvent RecargarGrillaProductos(_ProductosEnFactura)
      If _ModoEdicion Then
        _ModoEdicion = False
        Me.Close()
      Else
        UcStatusBar1.MostrarMensajeVerde("El producto se agregó correctamente a la factura.")
      End If
    Else
      UcStatusBar1.MostrarMensajeRojo("Debe seleccionar un producto.")
    End If
  End Sub

  'Private Sub txtCodigo_TextChanged(sender As System.Object, e As System.EventArgs) Handles txtCodigo.TextChanged
  '  'CargarGrid()
  'End Sub

  Private Sub txtDescripcion_Leave(sender As Object, e As System.EventArgs) Handles txtDescripcion.Leave
    CargarGrid()
  End Sub

  Private Sub txtDescripcion_TextChanged(sender As System.Object, e As System.EventArgs) Handles txtDescripcion.TextChanged
    '  CargarGrid()
  End Sub

  Private Sub CargarDatosDesdeControles()
    With ProductoSel
      .Precio = txtProdSelPrecio.Value
      .Cantidad = txtProdSelCantidad.Value
      .Descuentos = txtProdSelDesc.Value
      .Gastos = txtProdSelGastos.Value
    End With
  End Sub

  Private Sub LimpiarControles()
    txtProdSelPrecio.Value = 0
    txtProdSelCantidad.Value = 0
    txtProdSelDesc.Value = 0
    txtProdSelGastos.Value = 0
    txtProdSelSubTotal.Value = 0
    txtDescripcion.Text = ""
    txtCodigo.Text = ""
    grdDatos.DataSource = New vLstProductos
    grdDatos.DataBind()
    txtCodigo_Leave(Nothing, Nothing)
    txtCodigo.Focus()

  End Sub

  Private Sub LimpiarControlesProdcutoSeleccionado()
    txtProdSelPrecio.Value = 0
    txtProdSelCantidad.Value = 0
    txtProdSelDesc.Value = 0
    txtProdSelGastos.Value = 0
    txtProdSelSubTotal.Value = 0
    grpProdSel.Text = "Producto Seleccionado"
    txtCodigo.Focus()

  End Sub
  Private Function ExisteEnFactura(pProductoSeleccionado As vProducto) As vProducto
    Return (From PF In _ProductosEnFactura Where PF.MercaderiaId = pProductoSeleccionado.MercaderiaId
    Select PF).FirstOrDefault()
  End Function

  Private Sub btnCancelar_Click(sender As System.Object, e As System.EventArgs) Handles btnCancelar.Click
    'Me.Dispose()
    Me.Close()
  End Sub

  Private Sub txtCodigo_Leave(sender As System.Object, e As System.EventArgs) Handles txtCodigo.Leave
    CargarGrid()
  End Sub

  Private Sub btnProductoAlterntivo_Click(sender As System.Object, e As System.EventArgs) Handles btnProductoAlterntivo.Click
    With ProductoSel
      frmProductosAlternativosBuscar.GetProductosAlternativos(_ListPrecioId, .MercaderiaId, .Nombre, .MercaderiaNumero, Me)
    End With
  End Sub


  Private Sub grdDatos_AfterSelectChange(sender As System.Object, e As Infragistics.Win.UltraWinGrid.AfterSelectChangeEventArgs) Handles grdDatos.AfterSelectChange
    Dim ProductoFromRow As vProducto = Nothing
    If e Is Nothing Then
      If grdDatos.Rows.Count > 0 Then
        ProductoFromRow = CType(grdDatos.Rows(0).ListObject, vProducto)
        CargarControlesProducto(ProductoFromRow)
      Else
        LimpiarControlesProdcutoSeleccionado()
      End If
    ElseIf e.Type Is GetType(UltraGridRow) Then
      For Each oRow As UltraGridRow In Me.grdDatos.Selected.Rows
        ProductoFromRow = CType(oRow.ListObject, vProducto)
        If ProductoSel Is Nothing OrElse ProductoSel.MercaderiaId <> ProductoFromRow.MercaderiaId Then
          CargarControlesProducto(ProductoFromRow)
          '  _ProductosEnFactura.Find()      
        End If
      Next
    End If
  End Sub

  Private Sub CargarControlesProducto(pProductoFromRow As vProducto)
    ProductoSel = ExisteEnFactura(pProductoFromRow)
    If ProductoSel Is Nothing Then
      ProductoSel = vProducto.MappToNewvProduct(pProductoFromRow)
      AgregarAFactura = True
    Else
      AgregarAFactura = False
    End If
    With ProductoSel
      grpProdSel.Text = "Producto Seleccionado: " & .MercaderiaNumero & " - " & .Nombre
      txtProdSelPrecio.Value = .Precio
      txtProdSelCantidad.Value = .Cantidad
      txtProdSelDesc.Value = .Descuentos
      txtProdSelGastos.Value = .Gastos
      txtProdSelSubTotal.Value = .TotalLinea
      pProductoFromRow = Nothing
    End With
    ChequearStockProducto()
  End Sub

  Private Sub ChequearStockProducto()
    With ProductoSel
      .Cantidad = txtProdSelCantidad.Value
      If (.CantidadStock < 0) OrElse (.CantidadStock - txtProdSelCantidad.Value) < 0 Then
        btnProductoAlterntivo.Enabled = True
        btnAceptar.Enabled = False
      Else
        btnProductoAlterntivo.Enabled = False
        btnAceptar.Enabled = True
      End If
    End With
  End Sub

  'Private Sub frmProductosBuscar_Load(sender As Object, e As System.EventArgs) Handles Me.Load
  '  LimpiarControles()
  'End Sub

  Private Sub txtProdSelCantidad_AfterExitEditMode(sender As System.Object, e As System.EventArgs) Handles txtProdSelCantidad.AfterExitEditMode
    If ProductoSel IsNot Nothing Then
      ChequearStockProducto()
      With ProductoSel
        .Cantidad = txtProdSelCantidad.Value
        txtProdSelSubTotal.Value = .TotalLinea
      End With
    End If
  End Sub
  Private Sub txtProdSelDesc_AfterExitEditMode(sender As System.Object, e As System.EventArgs) Handles txtProdSelDesc.AfterExitEditMode
    If ProductoSel IsNot Nothing Then
      With ProductoSel
        .Descuentos = txtProdSelDesc.Value
        txtProdSelSubTotal.Value = .TotalLinea
      End With
    End If
  End Sub

  Private Sub txtProdSelGastos_AfterExitEditMode(sender As System.Object, e As System.EventArgs) Handles txtProdSelGastos.AfterExitEditMode
    If ProductoSel IsNot Nothing Then
      With ProductoSel
        .Gastos = txtProdSelGastos.Value
        txtProdSelSubTotal.Value = .TotalLinea
      End With
    End If
  End Sub

  Private Sub frmProductosBuscar_KeyDown(sender As System.Object, e As System.Windows.Forms.KeyEventArgs) Handles MyBase.KeyDown
    If Keys.F2 = e.KeyCode And btnAceptar.Enabled = True Then
      btnAceptar_Click(Nothing, Nothing)
    ElseIf Keys.Escape = e.KeyCode And btnCancelar.Enabled = True Then
      btnCancelar_Click(Nothing, Nothing)
    End If
  End Sub
End Class